/* Gauge - Performance Measurement Framework for Mobile Platforms
 * Copyright (C) 2013, Juha Hytonen <juha.a.hytonen@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gauge;

import org.joda.time.DateTime;

/**
 * Serializes measurements into strings and vice versa.
 * 
 * @see Measurement
 */
public final class MeasurementSerializer extends AbstractSerializer {
	
	private static final int NamePos = 0;
	private static final int TypePos = 1;
	private static final int TimestampPos = 2;
	private static final int ValuePos = 3;
	private static final int MeasurementUnitPos = 4;
	
	private Measurement measurement;
	private String measurementString;
	
	public MeasurementSerializer(Measurement measurement) {
		this.measurement = measurement;
		serialize();
	}
	
	private void serialize() {
		String name = measurement.GetName();
		String type = measurement.GetType().toString();
		String timestamp = convertToTimestamp(measurement.GetDateTime());
		String value = String.valueOf(measurement.GetValue());
		String measurementUnit = measurement.GetMeasurementUnit();
		
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(name);
		stringBuilder.append(DefaultSeparator);
		stringBuilder.append(type);
		stringBuilder.append(DefaultSeparator);
		stringBuilder.append(timestamp);
		stringBuilder.append(DefaultSeparator);
		stringBuilder.append(value);
		stringBuilder.append(DefaultSeparator);
		stringBuilder.append(measurementUnit);
		
		measurementString = stringBuilder.toString();
	}
	
	public MeasurementSerializer(String measurementString) {
		this.measurementString = measurementString;
		deserialize();
	}
	
	private void deserialize() {
		String[] measurementParts = measurementString.split(DefaultSeparator);
		String name = measurementParts[NamePos];
		Probe.Type type = Probe.Type.valueOf(measurementParts[TypePos]);
		DateTime date = convertToDateTime(measurementParts[TimestampPos]);
		int value = Integer.parseInt(measurementParts[ValuePos]);
		String measurementUnit = measurementParts[MeasurementUnitPos];
		
		measurement = new Measurement(name, type, date, value, measurementUnit);
	}
	
	public Measurement GetAsMeasurement() {
		return measurement;
	}
	
	public String GetAsString() {
		return measurementString;
	}

}
